# -*- coding: utf-8 -*-
'''
#----------------------------------------------------------------------------------------
# 功能：svn切换分支
#----------------------------------------------------------------------------------------
'''
import argparse
import shutil
from flib.utils import *

def user():
    return ",by:" + getenv("BUILD_USER",None) if getenv("BUILD_USER",None) else ""

@quit
def safe_exec_sh(cmds, logout=True):
    return execute(cmds=cmds, logout=logout)

def external_set(args):
    paths = args.external_path.split(",")
    values = args.external_value.split(",")
    if len(paths) != len(values):
        Log.log("external path and value not match.")
        exit(-1)
    if not args.external_host:
        Log.log("external dest path is need.")
        exit(-1)

    tmpdir = "svn-external-tmp"
    tmpfile = tmpdir + "/external.txt"
    if os.path.exists(tmpdir):
        shutil.rmtree(tmpdir, True)
    if not os.path.exists(tmpdir):
        os.makedirs(tmpdir)

    try:
        f = open(tmpfile, "a")
        for x in xrange(0, len(paths)):
            p = paths[x]
            v = values[x]
            f.write("{path} {url}\n".format(path=p, url=v))
        f.close()
        safe_exec_sh(cmds="svn co '{svn_host}/{host_url}' '{dest_path}' --depth empty".format(svn_host=args.svn_host, host_url=args.external_host, dest_path=tmpdir+"/dir"))
        safe_exec_sh(cmds="svn propset svn:externals '{dest_path}' -F '{value_file}'".format(dest_path=tmpdir+"/dir", value_file=tmpfile))
        safe_exec_sh(cmds="svn ci '{dest_path}' -m '{message}'".format(dest_path=tmpdir+"/dir", message=toGBK(args.external_message)))
        Log.log("外链设置成功")
    except Exception as e:
        raise e
    finally:
        pass

def delete_branchs(args):
    Log.log("查找是否存在分支{from_branch}".format(from_branch=args.from_branch))
    if args.from_branch + "/" in safe_exec_sh(cmds="svn list {svn_host}/branches".format(svn_host=args.svn_host), logout=False):
        safe_exec_sh("svn rm {svn_host}/branches/{from_branch} -m '{log}'".format(
            svn_host=args.svn_host, from_branch=args.from_branch, log=toGBK("删除分支") + args.from_branch))
        Log.log("删除分支成功{from_branch}".format(from_branch=args.from_branch))
    else:
        Log.log("分支{from_branch}不存在".format(from_branch=args.from_branch))

def delete_branchs_from_tag(args):
    Log.log("查找是否存在分支{from_branch}".format(from_branch=args.from_branch))
    if args.from_branch + "/" in safe_exec_sh(cmds="svn list {svn_host}/tags".format(svn_host=args.svn_host), logout=False):
        safe_exec_sh("svn rm {svn_host}/tags/{from_branch} -m '{log}'".format(
            svn_host=args.svn_host, from_branch=args.from_branch, log=toGBK("删除分支")+args.from_branch))
        Log.log("删除分支成功{from_branch}".format(from_branch=args.from_branch))
    else:
        Log.log("分支{from_branch}不存在".format(from_branch=args.from_branch))

def copy_branches(args):
    Log.log("查找是否存在旧的{to_branch}".format(to_branch=args.to_branch))
    if args.to_branch + "/" in safe_exec_sh(cmds="svn list {svn_host}/branches".format(svn_host=args.svn_host), logout=False):
        if args.backup:
            sdate = args.backup_suffix #datetime.datetime.now().strftime("%Y%m%d%H%M%S")
            Log.log("备份到tag下", "{to_branch}_{date}".format(to_branch=args.to_branch, date=sdate))
            safe_exec_sh("svn mv {svn_host}/branches/{to_branch} {svn_host}/tags/{to_branch}_{date} -m '{log}'".format(
                    svn_host=args.svn_host, to_branch=args.to_branch, date=sdate, log=toGBK("备份分支")))
        else:
            Log.log("删除分支", args.to_branch)
            safe_exec_sh("svn rm {svn_host}/branches/{to_branch} -m '{log}'".format(
                svn_host=args.svn_host, to_branch=args.to_branch, log=toGBK("删除分支")+args.to_branch))

    Log.log("切换分支")
    from_branch_path = "{svn_host}/branches/{from_branch}".format(svn_host=args.svn_host,from_branch=args.from_branch) if args.from_branch != "trunk" else "{svn_host}/trunk".format(svn_host=args.svn_host)
    safe_exec_sh("svn cp {from_branch_path} {svn_host}/branches/{to_branch} -m '{log}'".format(
        svn_host=args.svn_host, from_branch_path=from_branch_path, to_branch=args.to_branch, from_branch=args.from_branch, log=toGBK("从{from_branch}切换分支".format(from_branch=args.from_branch))))

    Log.log("切换分支成功 FROM: {from_branch}, TO:{to_branch}".format(from_branch=args.from_branch, to_branch=args.to_branch))    

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--svn-host", help="the svn host address", type=str, required=True)
    parser.add_argument("--svn-op", help="operation(copy, delete)", type=str, required=True)
    parser.add_argument("--from-branch", help="the svn branch which switch from", type=str)
    parser.add_argument("--to-branch", help="the svn branch which switch to", type=str)
    parser.add_argument("--backup-suffix", help="backup branch with suffix", type=str, default="")
    parser.add_argument("--external-host", help="path for external to set", type=str)
    parser.add_argument("--external-path", help="relative path for external to set", type=str)
    parser.add_argument("--external-value", help="external value to set", type=str)
    parser.add_argument("--external-message", help="external value to set", type=str, default="修改外链")
    parser.add_argument("--backup", help="backup it to tags before copy", action="store_true")

    args = parser.parse_args()

    if args.to_branch == args.from_branch and args.svn_op == "copy":
        Log.log("选择了相同的分支")
        exit(-1)

    if args.from_branch == "trunk" and args.svn_op == "delete":
        Log.log("不能删除trunk")
        exit(-1)

    if args.to_branch == "trunk":
        Log.log("不能从分支切到trunk")
        exit(-1)

    if args.svn_op == "external": external_set(args)
    elif args.svn_op == "delete-tag": delete_branchs_from_tag(args)
    else: delete_branchs(args) if args.svn_op == "delete" else copy_branches(args)
    


if __name__ == '__main__':
    main()
